<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        class LinkList {
            head = null

            constructor(data) {
                const newNode = new LinkList.Node(data)
                this.head = newNode
            }
                
            static Node = class Node {
                constructor(data) {
                    this.data = data
                    this.next = null
                }
            }
            
            add(data) {
                const newNode = new LinkList.Node(data)
                if (this.head === null) {
                    this.head = newNode
                    return this.head
                }
                
                let current = this.head
                while(current.next) {
                    current = current.next
                }
                current.next = newNode
                return this.head
            }

            // 反转链表
            reverse() {
                let current = this.head
                let prev = null

                while(current) {
                    let temp = current.next
                    current.next = prev
                    prev = current
                    current = temp
                }
                return prev
            }

            // 两两相交
            exchange() {
                // 添加一个虚拟头节点
                let newNode = new LinkList.Node(null)
                newNode.next = this.head
                this.head = newNode

                let temp = this.head
                while(temp.next && temp.next.next) {
                    let cur = temp.next.next
                    let prev = temp.next

                    prev.next = cur.next
                    cur.next = prev
                    temp.next = cur
                    temp = prev

                }
                return this.head.next
            }

            // 删除倒数第n个元素
            delAfterN(num) {
                // 创建虚拟头节点
                const newNode = new LinkList.Node(null)
                newNode.next = this.head
                this.head = newNode

                let current = this.head
                let slow = this.head
                while(num--) {
                    current = current.next
                }

                while(current.next) {
                    slow = slow.next
                    current = current.next
                }
                slow.next = slow.next.next

                return this.head.next
            }
        }
        const ll = new LinkList('aaa')
        ll.add('bbb')
        ll.add('ccc')
        ll.add('ddd')

        // const res = ll.reverse()
        // const res = ll.exchange()
        const res = ll.delAfterN(2)
        console.log(res)
    </script>
</body>
</html>